package com.sky.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.insert(dish);
        //插入数据后获取主键值
        Long ids = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null&&flavors.size()>0){
            //循环设置id值
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(ids);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否在起售状态
        for(Long id:ids){
            Dish dish = dishMapper.selectById(id);
            if(dish.getStatus()== StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前菜品是否有套餐关联
        LambdaQueryWrapper<SetmealDish> lam=new LambdaQueryWrapper<>();

        for(Long dishId:ids){
            lam.eq(SetmealDish::getDishId,dishId);
            SetmealDish setmealDish=setmealDishMapper.selectOne(lam);
            if(setmealDish!=null){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        //删除菜品
        dishMapper.deleteBatchIds(ids);
        //删除菜品对应的口味
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据ID查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO selectById(Long id) {
        Dish dish = dishMapper.selectById(id);
        LambdaQueryWrapper<DishFlavor> lam=new LambdaQueryWrapper<>();
        lam.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(lam);
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Override
    public void updateDishAndFlover(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        LambdaQueryWrapper<Dish> lam=new LambdaQueryWrapper<>();
        lam.eq(Dish::getId,dishDTO.getId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setUpdateTime(LocalDateTime.now());
        dishMapper.update(dish,lam);
        //删除原有的口味数据
        List<Long> ids=new ArrayList<>();
        ids.add(dishDTO.getId());
        dishFlavorMapper.deleteByDishIds(ids);
        //重新插入口味数据
        List<DishFlavor> flavors=dishDTO.getFlavors();
        if(flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 起售停售菜品
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish=new Dish();
        LambdaQueryWrapper<Category> lam= new LambdaQueryWrapper<>();
        Dish dish1 = dishMapper.selectById(id);
        Long categoryId = dish1.getCategoryId();
        lam.eq(Category::getId,categoryId);
        if(status==1){
            Category category = categoryMapper.selectOne(lam);
            if(category.getStatus()==0){
                throw new DeletionNotAllowedException(MessageConstant.CATEGORY_ENABLE_FAILED);
            }
        }
        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.updateById(dish);
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        LambdaQueryWrapper<Dish> lam=new LambdaQueryWrapper<>();
        if(dish.getName()!=null&&dish.getName()!=" "){
            lam.like(Dish::getName,dish.getName());
        }
        if(dish.getCategoryId()!=null){
            lam.eq(Dish::getCategoryId,dish.getCategoryId());
        }
        if(dish.getStatus()!=null){
            lam.eq(Dish::getStatus,dish.getStatus());
        }

        List<Dish> dishList = dishMapper.selectList(lam);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }
}
